# coding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
import multiprocessing
import numpy as np
import pandas as pd
from gm.api import *
import matplotlib.pyplot as plt
import os


def init(context):
    # 每月第一个交易日09:40:00的定时执行algo任务
    schedule(schedule_func=algo, date_rule='1m', time_rule='09:40:00')


def algo(context):
    # 获取当前时刻
    now = context.now
    # 获取上一个交易日
    last_day = get_previous_trading_date(exchange='SHSE', date=now)
    # 获取IT指数成份股
    stock300 = get_history_constituents(index='SZSE.399239', start_date=last_day,
                                        end_date=last_day)[0]['constituents'].keys()
    # 获取当天有交易的股票
    not_suspended_info = get_history_instruments(symbols=stock300, start_date=now, end_date=now)
    not_suspended_symbols = [item['symbol'] for item in not_suspended_info if not item['is_suspended']]
    fin = get_fundamentals(table='trading_derivative_indicator', symbols=not_suspended_symbols,
                           start_date=now, end_date=now, fields='PELFYNPAAEI',
                           filter='PELFYNPAAEI >0 or PELFYNPAAEI <0', order_by='PELFYNPAAEI', df=True)
    long = len(fin)
    print(context)
    if context.stockrange == 0.1:
        stockpool = list(fin.symbol)[0:int(long * context.stockrange) - 1]
    else:
        stockpool = list(fin.symbol)[int(long * (context.stockrange - 0.1)) - 1:int(long * context.stockrange) - 1]
    # 清仓
    order_close_all()

    # 获取股票的权重
    percent = 1.0 / len(stockpool)
    # 买在标的池中的股票
    for symbol in stockpool:
        order_target_percent(symbol=symbol, percent=percent, order_type=OrderType_Market,
                             position_side=PositionSide_Long)


# 获取每次回测的报告数据
def on_backtest_finished(context, indicator):
    data = [indicator['pnl_ratio'], indicator['pnl_ratio'] + 0.189, indicator['pnl_ratio_annual'],
            indicator['sharp_ratio'],
            indicator['max_drawdown'],
            context.stockrange]
    # 将回测报告加入全局list，以便记录
    context.list.append(data)


def run_strategy(stockrange, a_list):


    from gm.model.storage import context

    # 用context传入参数
    context.stockrange = stockrange
    # a_list一定要传入
    context.list = a_list
if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename=(os.path.basename(__file__)),
        # filename=('程序6_2策略.py'),
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2016-01-01 09:00:00',
        backtest_end_time='2018-12-31 15:00:00',
        backtest_initial_cash=20000,
        backtest_adjust=ADJUST_PREV,
    )

# if __name__ == '__main__':
#
#     # 生成全局list
#     manager = multiprocessing.Manager()
#     a_list = manager.list()
#     # 循环输入参数数值回测
#     for stockrange in np.arange(0.1, 1.1, 0.1):
#         print(stockrange)
#     process = multiprocessing.Process(target=run_strategy, args=(stockrange, a_list))
#     process.start()
#     process.join()
#     # 回测报告转化成DataFrame格式
#     a_list = np.array(a_list)
#     final = pd.DataFrame(a_list,
#                          columns=['pnl_ratio', 'Alpha', 'pnl_ratio_annual', 'sharp_ratio', 'max_drawdown',
#                                   'stockrange'])
#     fig = plt.figure(figsize=(12, 6))
#     fig.set_facecolor('white')
#     plt.bar(final.loc[final.Alpha > 0].index, final.loc[final.Alpha > 0].Alpha, align='center', color='r', width=0.3)
#     plt.bar(final.loc[final.Alpha < 0].index, final.loc[final.Alpha < 0].Alpha, align='center', color='g', width=0.3)
#     plt.title('PELFYNPAAEI')
#     plt.show()
#     print(final)
